package com.shadt.sms.service.impl;

import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.shadt.core.model.Json;
import com.shadt.sms.dao.SysSmsConfigDao;
import com.shadt.sms.dao.SysSmsRecordDao;
import com.shadt.sms.entity.SysSmsConfig;
import com.shadt.sms.entity.SysSmsRecord;
import com.shadt.sms.service.SendMsg;
import com.shadt.sms.util.SendUtil;

/**
 * 短信实现类
 * 
 * @author SongR
 *
 */
@Service
public class SendMsgImpl implements SendMsg {

	Logger log = Logger.getLogger(this.getClass());
	@Autowired
	SysSmsConfigDao dao;

	@Autowired	
	SysSmsRecordDao rdao;
	
	/**
	 * 实现发送短信
	 */
	public Json send(String phone) throws Exception {
		String ss = dao.getR("smsconfig",0);
		SysSmsConfig s = new SysSmsConfig();
		int checknum = new Random().nextInt(8999) + 1000;
		String param="";
		if("".equals(ss)||null==ss){
			List<SysSmsConfig> sc = dao.find("from SysSmsConfig where status = 0 order by id");
			if(sc.size()>0){
				s = sc.get(0);
				dao.deleteR("smsconfig");
				dao.addR("smsconfig", s);
			}
		}else{
			s =JSONObject.parseObject(ss, SysSmsConfig.class);
		}
		String content = s.getContent().replace("checknum", checknum+"");
		param= "action=send&userid=" + s.getUserid() + "&account=" + s.getAccount() + "&password="
				+ s.getPassword() + "&mobile=" + phone + "&content="
				+ URLEncoder.encode(content, "utf-8");
		Json j = SendUtil.parse(SendUtil.request(s.getUrl(), param));
		if(j.isSuccess()){
			List<SysSmsRecord> rs = rdao.find("from SysSmsRecord where status!=0 and phone='"+phone+"'");
			for (SysSmsRecord sss : rs) {
				sss.setStatus(0);
				rdao.update(sss);
			}
			SysSmsRecord record = new SysSmsRecord();
			record.setCode(checknum+"");
			record.setPhone(phone);
			record.setSendtime(new Date());
			record.setStatus(1);
			rdao.save(record);
			rdao.addR(phone+checknum,record);
			j.setObj(record);
		}
//		j.setObj(checknum);
		return j;
	}

	/**
	 * 修改验证码状态
	 */
	public void setStatus(String phone , String code){
		try {
			List<SysSmsRecord> rs = rdao.find("from SysSmsRecord where status!=0 and phone='"+phone+"'");
			for (SysSmsRecord sss : rs) {
				sss.setStatus(0);
				rdao.update(sss);
			}
			rdao.deleteR(phone+code);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 判断验证码
	 */
	public boolean check(String phone,String code) throws Exception {
		String redisr = rdao.getR(phone+code,0);
		if("".equals(redisr)||null==redisr){
			List<SysSmsRecord> rs = rdao.find("from SysSmsRecord where status!=0 and phone='"+phone+"' and code='"+code+"'");
			if(rs.size()>0){
				return true;
			}
		}else{
			return true;
		}
		return false;
	}

}
